<template>
  <div>
    <el-row class="tigan">
      试题题干：
      <div class="editorBox">
        <editorWanXingXuantian ref="editorTK" :form="modelValue" v-model="modelValue.subjectEditorValue" :height="200"
          :tiankong="true" @blurIpt="blurIpt" @addTK="addTK" @handVal="handVal" @input="tiganInp"
          @keyup.enter.native="tiganInp" @getVal="getVal" />
      </div>
      <el-alert style="margin: 10px;" :closable="false" center
        title="请在题干的适当位置放置光标，然后再点新增填空，增加一个空。请勿手动修改红色字体，如要删除填空请点击下方操作栏对应的删除按钮!" type="warning" show-icon />
    </el-row>
    <div class="options mt10">
      <div class="left">
        答案选项：
      </div>
      <table class="right">
        <thead>
          <tr class="optionsTitle">
            <th style="width: 3%;"></th>
            <th style="width: 5%;">题号</th>
            <th style="width: 40%;">选项</th>
            <th style=" width: 10%;">正确答案</th>
            <th style="width: 10%;">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr class="option" v-for="(option, i) in props.modelValue.options" :key="option.id">
            <td></td>
            <td style="font-size: 20px; font-weight: bold;">{{ i + 1 }}.</td>
            <td>
              <div class="op" v-for="(op, ii) in option.options" :key="ii">
                <div style="width: 30px;text-align: center;">{{ String.fromCharCode(64 + parseInt(ii + 1)) }}.</div>
                <el-input :disabled="!getShow(i)" style="width: 60%;" @input="xuanTianOptions" v-model="op.text"
                  placeholder="点击编辑"></el-input>
                <div class="hoverBox" v-if="getShow(i)">
                  <el-tooltip effect="light" content="添加" placement="top-start">
                    <el-icon color="#409EFF" class="iconS" @click="editOp('add', option.options, ii)">
                      <Plus />
                    </el-icon>
                  </el-tooltip>
                  <el-tooltip effect="light" content="删除" placement="top-start">
                    <el-icon color="#f56c6c" class="iconS" @click="editOp('del', option.options, ii)">
                      <Delete />
                    </el-icon>
                  </el-tooltip>
                </div>
              </div>
            </td>
            <td>
              <radio-group :options="option.options" />
            </td>
            <td><el-tooltip effect="light" content="删除" placement="top-start">
                <el-icon style="color:#ff404a;cursor: pointer;" @click="delBack(option, i)">
                  <Delete />
                </el-icon>
              </el-tooltip>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <el-row style="border-top: 1px dashed #dcdfe8;;padding-top:10px;margin-top:20px;">
      <el-col :span="4">
        <el-button type="primary" text :icon="Plus" @click="addAnalysis">添加试题解析</el-button>
      </el-col>
    </el-row>
    <el-row v-if="modelValue.explainEditorShow" class="mt20">
      试题解析：
      <div class="editorBox">
        <TinymceEditor ref="editor" v-model="modelValue.explainEditorValue" :height="80" />
      </div>
    </el-row>
  </div>
</template>
<script setup>
import { deep } from '../../utils/paper'
import { getCurrentInstance,  toRefs, ref, reactive, onMounted, onBeforeUnmount, watch } from 'vue'
import RadioGroup from '../component/radio/index.vue'
import {
  Plus,
  CloseBold,
  ArrowDownBold,
  Document,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import TinymceEditor from "../component/Editor/index.vue";
import editorWanXingXuantian from '../component/Editor/editorWanxingXuantian.vue';
const emit = defineEmits(["update:modelValue", 'updateTiGan']);
const props = defineProps({
  modelValue: {
    type: [String, Object, Array],
    default: null,
  },
  serialNumber: {
    type: String,
    default: null
  }
});
onMounted(() => {
  setTimeout(() => {
    if (props.serialNumber) {
      let content = editorTK.value.getContent();
      props.modelValue.options.forEach((res) => {
        res.maxText = getMaxText(res.optionUuid, content);
      });
    }
  }, 2000);
});
const getMaxText = (uuid, val) => {
  return val.slice(
    val.indexOf(uuid) - 10,
    val.indexOf("</span>", val.indexOf(uuid)) + 7
  );
};
const addAnalysis = () => {
  //添加试题解析
  props.modelValue.explainEditorShow = !props.modelValue.explainEditorShow;
  props.modelValue.explainEditorValue = "";
};
watch(
  () => props.modelValue,
  (newVal, oldVal) => {
    props.modelValue.subjectEditorValue = editorTK.value.getContent();
    emit("update:modelValue", props.modelValue);
  },
  { deep: true }
);
const editorTK = ref(null);
const handVal = (val) => {

};
const addTK = (val) => {
  props.modelValue.options.push(val)
  xuanTianOptions()
};
const getShow = (i) => {
  return props.modelValue.questionTypeBase === 'wan_xing' || (props.modelValue.questionTypeBase === 'xuan_tian' && i === 0);
}
const tiganInp = () => {

};
const getVal = (val) => {

};
const blurIpt = () => {
  anewSort()
}
const xuanTianOptions = () => {
  if (['xuan_tian'].includes(props.modelValue.questionTypeBase)) {
    //如果是选填题，就把所有小选项变成和第一个小选项一致
    props.modelValue.options.forEach((opi, i) => {
      if (i != 0) {
        const op = opi.options.filter(ii => ii.isRight)
        opi.options = JSON.parse(JSON.stringify(props.modelValue.options[0].options))
        opi.options.map(res => res.isRight = false)
        opi.options[op[0].id] ? opi.options[op[0].id].isRight = true : opi.options[0].isRight = true
      }
    })
  }
}
const delBack = (option, i) => {//删除大选项
  if (props.modelValue.options.length === 1) {
    ElMessage.error('最少有一个选项!');
    return;
  }
  const deletedItem = props.modelValue.options.splice(i, 1)[0]; // 删除数组里面对应的数据
  // 根据id删除题干里的数据并重新赋值给题干
  const optionUuid = deletedItem.optionUuid;
  const regex = new RegExp(`<span id="${optionUuid}-wrapper".*?>(.*?)<\/span>`);
  const updatedTiGan = props.modelValue.subjectEditorValue.replace(regex, '');
  emit('updateTiGan', updatedTiGan);
  anewSort();
  xuanTianOptions()
}
const anewSort = () => {//重新初始化题干与选项配对   并清空用户单方面删除题干后选项无法绑定题干造成的选项中错误数据
  props.modelValue.options = props.modelValue.options.filter((res) => {
    return props.modelValue.subjectEditorValue.includes(res.optionUuid);
  }).map((res, index) => {
    const oldId = JSON.parse(JSON.stringify(res.id));
    res.id = index + 1;
    res.maxText = res.maxText.replace(`{{${oldId}}}`, `{{${res.id}}}`);
    const updatedValue = props.modelValue.subjectEditorValue.replace(
      props.modelValue.subjectEditorValue.match(new RegExp(`<span id="${res.optionUuid}-wrapper".*?>(.*?)<\/span>`))[0],
      res.maxText
    );
    emit('updateTiGan', updatedValue);
    return res;
  });
  editorTK.value.song(props.modelValue.subjectEditorValue); //文本框更新最新数据
}
const editOp = (type, op, ii) => {//添加和删除小选项
  if (type == 'add') {
    op.splice(ii + 1, 0, { isRight: false, text: '', id: 1 });
  } else {
    if (op.length == 1) return ElMessage.error('最少有一个选项!')
    let del = op.splice(ii, 1);//删除选项
    if (del[0].isRight) op[0].isRight = true //如果删除的选项是正确答案那么就把第一个设置为正确答案
  }
  op.forEach((item, index) => item.id = index);
  xuanTianOptions()
}
</script>

<style scoped lang="scss">
.options {
  display: flex;

  .left {
    width: 80px;
  }

  .option {
    border-bottom: 1px dashed #ccc;
  }

  .right {
    width: calc(100% - 80px);
    border: 1px solid #eeeeee;

    .optionsTitle {
      height: 43px;
      background-color: #eeeeee;
      font-size: 16px;
      font-weight: bold;
      padding: 0 20px;
      text-align: left;
    }

    .op {
      display: flex;
      align-items: center;
      margin: 10px;
      font-weight: bold;
      overflow: hidden;

    }

    tbody {
      align-items: center;
    }
  }
}

.hoverBox {
  width: 10%;
  display: flex;
  justify-content: space-around;
  transition: all .3s ease-in-out;
  opacity: 0;
}

.iconS {
  font-size: 18px !important;
  cursor: pointer;
}

.option:hover .hoverBox {
  opacity: 1;
}

.center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.alCenter {
  display: flex;
  align-items: center;
}

.dengxiao {
  display: flex;
  align-items: center;
}

.showOp {
  opacity: 0;
  transition: all 0.5s;
}

.hoverOptions:hover .showOp {
  opacity: 1;
}

.centerOp {
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.hoverOptions:hover .feedbackIcon {
  color: #409eff !important;
}
</style>